{% extends "base.html" %}

{% block title %}系统配置 - 梦幻西游数字资产管理系统{% endblock %}

{% block mobile_title %}系统配置{% endblock %}

{% block content %}
<div class="container-fluid settings-page">
    <h2 class="page-title">⚙️ 系统配置</h2>
    
    <!-- 导航标签 -->
    <ul class="nav nav-tabs settings-tabs" id="configTabs" role="tablist">
        <li class="nav-item" role="presentation">
            <button class="nav-link active text-dark" id="server-tab" data-bs-toggle="tab" data-bs-target="#server-panel" type="button" role="tab">
                🖥️ 服务器管理
            </button>
        </li>
        <li class="nav-item" role="presentation">
            <button class="nav-link text-dark" id="menpai-tab" data-bs-toggle="tab" data-bs-target="#menpai-panel" type="button" role="tab">
                ⚔️ 门派管理
            </button>
        </li>
        <li class="nav-item" role="presentation">
            <button class="nav-link text-dark" id="tasks-tab" data-bs-toggle="tab" data-bs-target="#tasks-panel" type="button" role="tab">
                📋 任务管理
            </button>
        </li>
        <li class="nav-item" role="presentation">
            <button class="nav-link text-dark" id="jjl-tab" data-bs-toggle="tab" data-bs-target="#jjl-panel" type="button" role="tab">
                🔐 将军令管理
                </button>
        </li>
        <li class="nav-item" role="presentation">
            <button class="nav-link text-dark" id="house-tab" data-bs-toggle="tab" data-bs-target="#house-panel" type="button" role="tab">
                🏠 房屋信息管理
                </button>
        </li>
        <li class="nav-item" role="presentation">
            <button class="nav-link text-dark" id="roleFunc-tab" data-bs-toggle="tab" data-bs-target="#roleFunc-panel" type="button" role="tab">
                👥 角色作用管理
                </button>
        </li>
    </ul>

    <!-- 标签页内容 -->
    <div class="tab-content" id="configTabContent">
        <!-- 服务器管理 -->
        <div class="tab-pane fade show active" id="server-panel" role="tabpanel">
            <div class="card">
                <div class="card-header bg-primary text-white d-flex justify-content-between align-items-center">
                    <h5 class="mb-0">🖥️ 服务器信息管理</h5>
                    <div>
                        <button class="btn btn-light btn-sm" onclick="showAddModal('server')">
                    <i class="bi bi-plus-circle"></i> 添加服务器
                </button>
            </div>
                </div>
                <div class="card-body">
            <div class="table-responsive">
                <table class="table table-hover align-middle">
                    <thead>
                        <tr>
                            <th>服务器名称</th>
                            <th>开服时间</th>
                            <th>状态</th>
                            <th>备注</th>
                                    <th style="width: 150px;">操作</th>
                        </tr>
                    </thead>
                    <tbody id="serverTableBody">
                                <tr><td colspan="5" class="text-center">加载中...</td></tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>

        <!-- 门派管理 -->
        <div class="tab-pane fade" id="menpai-panel" role="tabpanel">
            <div class="card">
                <div class="card-header bg-success text-white d-flex justify-content-between align-items-center">
                    <h5 class="mb-0">⚔️ 门派信息管理</h5>
                    <div>
                        <button class="btn btn-light btn-sm" onclick="showAddModal('menpai')">
                            <i class="bi bi-plus-circle"></i> 添加门派
                        </button>
                    </div>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-hover align-middle">
                            <thead>
                                <tr>
                                    <th>门派名称</th>
                                    <th>种族</th>
                                    <th>门派地点</th>
                                    <th>描述</th>
                                    <th style="width: 150px;">操作</th>
                                </tr>
                            </thead>
                            <tbody id="menpaiTableBody">
                                <tr><td colspan="5" class="text-center">加载中...</td></tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>

        <!-- 任务管理 -->
        <div class="tab-pane fade" id="tasks-panel" role="tabpanel">
            <div class="card">
                <div class="card-header bg-info text-white d-flex justify-content-between align-items-center">
                    <h5 class="mb-0">📋 任务信息管理</h5>
                    <div>
                        <button class="btn btn-light btn-sm" onclick="showAddModal('task')">
                            <i class="bi bi-plus-circle"></i> 添加任务
                        </button>
                    </div>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-hover align-middle">
                            <thead>
                                <tr>
                                    <th>任务名称</th>
                                    <th>任务类型</th>
                                    <th>等级范围</th>
                                    <th>每日次数</th>
                                    <th>预计耗时(分钟)</th>
                                    <th>状态</th>
                                    <th style="width: 150px;">操作</th>
                                </tr>
                            </thead>
                            <tbody id="tasksTableBody">
                                <tr><td colspan="7" class="text-center">加载中...</td></tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>

        <!-- 将军令管理 -->
        <div class="tab-pane fade" id="jjl-panel" role="tabpanel">
            <div class="card">
                <div class="card-header bg-warning text-dark d-flex justify-content-between align-items-center">
                    <h5 class="mb-0">🔐 将军令管理</h5>
                    <div>
                        <button class="btn btn-dark btn-sm" onclick="showAddModal('jjl')">
                            <i class="bi bi-plus-circle"></i> 添加将军令
                        </button>
                    </div>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-hover align-middle">
                            <thead>
                                <tr>
                                    <th>手机号</th>
                                    <th>设备</th>
                                    <th>状态</th>
                                    <th>备注</th>
                                    <th style="width: 150px;">操作</th>
                                </tr>
                            </thead>
                            <tbody id="jjlTableBody">
                                <tr><td colspan="5" class="text-center">加载中...</td></tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>

        <!-- 房屋信息管理 -->
        <div class="tab-pane fade" id="house-panel" role="tabpanel">
            <div class="card">
                <div class="card-header bg-danger text-white d-flex justify-content-between align-items-center">
                    <h5 class="mb-0">🏠 房屋信息管理</h5>
                    <div>
                        <button class="btn btn-light btn-sm" onclick="showAddModal('house')">
                            <i class="bi bi-plus-circle"></i> 添加房屋信息
                        </button>
                    </div>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-hover align-middle">
                            <thead>
                                <tr>
                                    <th>房屋规模</th>
                                    <th>风水等级</th>
                                    <th>建造费用</th>
                                    <th>最大空间</th>
                                    <th>房主</th>
                                    <th style="width: 150px;">操作</th>
                                </tr>
                            </thead>
                            <tbody id="houseTableBody">
                                <tr><td colspan="6" class="text-center">加载中...</td></tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>

        <!-- 角色作用管理 -->
        <div class="tab-pane fade" id="roleFunc-panel" role="tabpanel">
            <div class="card">
                <div class="card-header bg-secondary text-white d-flex justify-content-between align-items-center">
                    <h5 class="mb-0">👥 角色作用管理</h5>
                    <div>
                        <button class="btn btn-light btn-sm" onclick="showAddModal('roleFunc')">
                            <i class="bi bi-plus-circle"></i> 添加角色作用
                        </button>
                    </div>
                                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-hover align-middle">
                            <thead>
                                <tr>
                                    <th>角色作用</th>
                                    <th>备注</th>
                                    <th style="width: 150px;">操作</th>
                        </tr>
                            </thead>
                            <tbody id="roleFuncTableBody">
                                <tr><td colspan="3" class="text-center">加载中...</td></tr>
                    </tbody>
                </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 通用模态框 -->
<div class="modal fade" id="configModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="modalTitle">添加</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body" id="modalBody">
                <!-- 动态内容 -->
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="saveBtn" onclick="saveConfig()">保存</button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
let configModal = null;
let currentType = '';
let currentEditId = null;

$(document).ready(function() {
    configModal = new bootstrap.Modal(document.getElementById('configModal'));
    loadServers();
});

// 标签页切换时加载对应数据
$('#configTabs button[data-bs-toggle="tab"]').on('shown.bs.tab', function (e) {
    const target = $(e.target).attr('data-bs-target');
    if (target === '#menpai-panel') loadMenpai();
    else if (target === '#tasks-panel') loadTasks();
    else if (target === '#jjl-panel') loadJiangjunling();
    else if (target === '#house-panel') loadHouses();
    else if (target === '#roleFunc-panel') loadRoleFunctions();
});

// ==================== 服务器管理 ====================
async function loadServers() {
    try {
        const data = await apiRequest('/api/servers');
        const servers = data.data;
        
        if (servers.length === 0) {
            $('#serverTableBody').html('<tr><td colspan="5" class="text-center py-4">暂无数据</td></tr>');
            return;
        }
        
        let html = '';
        servers.forEach(s => {
            const statusBadge = s.status === '正常' ? 
                '<span class="badge bg-success">正常</span>' : 
                s.status === '维护' ?
                '<span class="badge bg-warning">维护</span>' :
                '<span class="badge bg-danger">停服</span>';
            
            html += `
                <tr>
                    <td><strong>${s.server_name}</strong></td>
                    <td>${s.server_start_time || '-'}</td>
                    <td>${statusBadge}</td>
                    <td>${s.remarks || '-'}</td>
                    <td>
                        <button class="btn btn-sm btn-outline-primary" onclick="editServer('${s.id}')">
                            <i class="bi bi-pencil"></i>
                        </button>
                        <button class="btn btn-sm btn-outline-danger" onclick="deleteItem('server', '${s.id}', '${s.server_name}')">
                            <i class="bi bi-trash"></i>
                        </button>
                    </td>
                </tr>
            `;
        });
        
        $('#serverTableBody').html(html);
    } catch (error) {
        console.error('加载服务器列表失败:', error);
        $('#serverTableBody').html('<tr><td colspan="5" class="text-center text-danger">加载失败</td></tr>');
    }
}

async function editServer(id) {
    const data = await apiRequest('/api/servers');
    const server = data.data.find(s => s.id === id);
    
    if (server) {
        currentType = 'server';
        currentEditId = id;
        $('#modalTitle').text('✏️ 编辑服务器');
        $('#modalBody').html(`
            <div class="mb-3">
                <label class="form-label">服务器名称 *</label>
                <input type="text" class="form-control" id="serverName" value="${server.server_name}" required>
            </div>
            <div class="mb-3">
                <label class="form-label">开服时间</label>
                <input type="date" class="form-control" id="serverStartTime" value="${server.server_start_time || ''}">
            </div>
            <div class="mb-3">
                <label class="form-label">状态</label>
                <select class="form-select" id="serverStatus">
                    <option value="正常" ${server.status === '正常' ? 'selected' : ''}>正常</option>
                    <option value="维护" ${server.status === '维护' ? 'selected' : ''}>维护</option>
                    <option value="停服" ${server.status === '停服' ? 'selected' : ''}>停服</option>
                </select>
            </div>
            <div class="mb-3">
                <label class="form-label">备注</label>
                <textarea class="form-control" id="serverRemarks" rows="3">${server.remarks || ''}</textarea>
            </div>
        `);
        configModal.show();
    }
}

// ==================== 门派管理 ====================
async function loadMenpai() {
    try {
        const data = await apiRequest('/api/menpai');
        const menpai = data.data;
        
        if (menpai.length === 0) {
            $('#menpaiTableBody').html('<tr><td colspan="5" class="text-center py-4">暂无数据</td></tr>');
            return;
        }
        
        let html = '';
        menpai.forEach(m => {
            const raceBadge = m.race === '人族' ? 'bg-primary' : m.race === '仙族' ? 'bg-info' : 'bg-danger';
            html += `
                <tr>
                    <td><strong>${m.name}</strong></td>
                    <td><span class="badge ${raceBadge}">${m.race}</span></td>
                    <td>${m.location}</td>
                    <td>${m.description || '-'}</td>
                    <td>
                        <button class="btn btn-sm btn-outline-primary" onclick="editMenpai(${m.id})">
                            <i class="bi bi-pencil"></i>
                        </button>
                        <button class="btn btn-sm btn-outline-danger" onclick="deleteItem('menpai', ${m.id}, '${m.name}')">
                            <i class="bi bi-trash"></i>
                        </button>
                    </td>
                </tr>
            `;
        });
        
        $('#menpaiTableBody').html(html);
    } catch (error) {
        console.error('加载门派列表失败:', error);
        $('#menpaiTableBody').html('<tr><td colspan="5" class="text-center text-danger">加载失败</td></tr>');
    }
}

async function editMenpai(id) {
    const data = await apiRequest('/api/menpai');
    const menpai = data.data.find(m => m.id === id);
    
    if (menpai) {
        currentType = 'menpai';
        currentEditId = id;
        $('#modalTitle').text('✏️ 编辑门派');
        $('#modalBody').html(`
            <div class="mb-3">
                <label class="form-label">门派名称 *</label>
                <input type="text" class="form-control" id="menpaiName" value="${menpai.name}" required>
            </div>
            <div class="mb-3">
                <label class="form-label">种族 *</label>
                <select class="form-select" id="menpaiRace" required>
                    <option value="人族" ${menpai.race === '人族' ? 'selected' : ''}>人族</option>
                    <option value="仙族" ${menpai.race === '仙族' ? 'selected' : ''}>仙族</option>
                    <option value="魔族" ${menpai.race === '魔族' ? 'selected' : ''}>魔族</option>
                </select>
            </div>
            <div class="mb-3">
                <label class="form-label">门派地点 *</label>
                <input type="text" class="form-control" id="menpaiLocation" value="${menpai.location}" required>
            </div>
            <div class="mb-3">
                <label class="form-label">描述</label>
                <textarea class="form-control" id="menpaiDescription" rows="3">${menpai.description || ''}</textarea>
            </div>
        `);
        configModal.show();
    }
}

// ==================== 任务管理 ====================
async function loadTasks() {
    try {
        const data = await apiRequest('/api/tasks-list');
        const tasks = data.data;
        
        if (tasks.length === 0) {
            $('#tasksTableBody').html('<tr><td colspan="7" class="text-center py-4">暂无数据</td></tr>');
        return;
    }
    
        let html = '';
        tasks.forEach(t => {
            const activeBadge = t.is_active === 'TRUE' ? 
                '<span class="badge bg-success">启用</span>' : 
                '<span class="badge bg-secondary">禁用</span>';
            html += `
                <tr>
                    <td><strong>${t.task_name}</strong></td>
                    <td><span class="badge bg-info">${t.task_type}</span></td>
                    <td>${t.min_level}-${t.max_level}</td>
                    <td>${t.daily_limit}</td>
                    <td>${t.duration_minutes || '-'}</td>
                    <td>${activeBadge}</td>
                    <td>
                        <button class="btn btn-sm btn-outline-primary" onclick="editTask('${t.task_id}')">
                            <i class="bi bi-pencil"></i>
                        </button>
                        <button class="btn btn-sm btn-outline-danger" onclick="deleteItem('task', '${t.task_id}', '${t.task_name}')">
                            <i class="bi bi-trash"></i>
                        </button>
                    </td>
                </tr>
            `;
        });
        
        $('#tasksTableBody').html(html);
    } catch (error) {
        console.error('加载任务列表失败:', error);
        $('#tasksTableBody').html('<tr><td colspan="7" class="text-center text-danger">加载失败</td></tr>');
    }
}

async function editTask(taskId) {
    const data = await apiRequest('/api/tasks-list');
    const task = data.data.find(t => t.task_id === taskId);
    
    if (task) {
        currentType = 'task';
        currentEditId = taskId;
        $('#modalTitle').text('✏️ 编辑任务');
        $('#modalBody').html(`
            <div class="row">
                <div class="col-md-12 mb-3">
                    <label class="form-label">任务名称 *</label>
                    <input type="text" class="form-control" id="taskName" value="${task.task_name}" required>
                </div>
                <div class="col-md-6 mb-3">
                    <label class="form-label">任务类型 *</label>
                    <select class="form-select" id="taskType" required>
                        <option value="日常" ${task.task_type === '日常' ? 'selected' : ''}>日常</option>
                        <option value="师门" ${task.task_type === '师门' ? 'selected' : ''}>师门</option>
                        <option value="副本" ${task.task_type === '副本' ? 'selected' : ''}>副本</option>
                        <option value="活动" ${task.task_type === '活动' ? 'selected' : ''}>活动</option>
                        <option value="剧情" ${task.task_type === '剧情' ? 'selected' : ''}>剧情</option>
                        <option value="奇遇" ${task.task_type === '奇遇' ? 'selected' : ''}>奇遇</option>
                        <option value="帮派" ${task.task_type === '帮派' ? 'selected' : ''}>帮派</option>
                        <option value="周末" ${task.task_type === '周末' ? 'selected' : ''}>周末</option>
                    </select>
                </div>
                <div class="col-md-3 mb-3">
                    <label class="form-label">最低等级 *</label>
                    <input type="text" class="form-control" id="taskMinLevel" value="${task.min_level}" required>
                </div>
                <div class="col-md-3 mb-3">
                    <label class="form-label">最高等级</label>
                    <input type="text" class="form-control" id="taskMaxLevel" value="${task.max_level}">
                </div>
                <div class="col-md-6 mb-3">
                    <label class="form-label">每日次数</label>
                    <input type="text" class="form-control" id="taskDailyLimit" value="${task.daily_limit}">
                </div>
                <div class="col-md-6 mb-3">
                    <label class="form-label">预计耗时(分钟)</label>
                    <input type="text" class="form-control" id="taskDuration" value="${task.duration_minutes || ''}">
                </div>
                <div class="col-12 mb-3">
                    <label class="form-label">是否启用</label>
                    <select class="form-select" id="taskIsActive">
                        <option value="TRUE" ${task.is_active === 'TRUE' ? 'selected' : ''}>启用</option>
                        <option value="FALSE" ${task.is_active === 'FALSE' ? 'selected' : ''}>禁用</option>
                    </select>
                </div>
            </div>
        `);
        configModal.show();
    }
}

// ==================== 将军令管理 ====================
async function loadJiangjunling() {
    try {
        const data = await apiRequest('/api/jiangjunling');
        const jjl = data.data;
        
        if (jjl.length === 0) {
            $('#jjlTableBody').html('<tr><td colspan="5" class="text-center py-4">暂无数据</td></tr>');
            return;
        }
        
        let html = '';
        jjl.forEach(j => {
            const statusBadge = j.status === '生效' ? 
                '<span class="badge bg-success">生效</span>' : 
                '<span class="badge bg-secondary">失效</span>';
            html += `
                <tr>
                    <td>${j.phone}</td>
                    <td>${j.device || '-'}</td>
                    <td>${statusBadge}</td>
                    <td>${j.remark || '-'}</td>
                    <td>
                        <button class="btn btn-sm btn-outline-primary" onclick="editJiangjunling(${j.id})">
                            <i class="bi bi-pencil"></i>
                        </button>
                        <button class="btn btn-sm btn-outline-danger" onclick="deleteItem('jjl', ${j.id}, '${j.phone}')">
                            <i class="bi bi-trash"></i>
                        </button>
                    </td>
                </tr>
            `;
        });
        
        $('#jjlTableBody').html(html);
    } catch (error) {
        console.error('加载将军令列表失败:', error);
        $('#jjlTableBody').html('<tr><td colspan="5" class="text-center text-danger">加载失败</td></tr>');
    }
}

async function editJiangjunling(id) {
    const data = await apiRequest('/api/jiangjunling');
    const jjl = data.data.find(j => j.id === id);
    
    if (jjl) {
        currentType = 'jjl';
        currentEditId = id;
        $('#modalTitle').text('✏️ 编辑将军令');
        $('#modalBody').html(`
            <div class="mb-3">
                <label class="form-label">手机号 *</label>
                <input type="text" class="form-control" id="jjlPhone" value="${jjl.phone}" required>
            </div>
            <div class="mb-3">
                <label class="form-label">设备</label>
                <input type="text" class="form-control" id="jjlDevice" value="${jjl.device || ''}" placeholder="例如：iPhone 13 Pro">
            </div>
            <div class="mb-3">
                <label class="form-label">状态 *</label>
                <select class="form-select" id="jjlStatus" required>
                    <option value="生效" ${jjl.status === '生效' ? 'selected' : ''}>生效</option>
                    <option value="失效" ${jjl.status === '失效' ? 'selected' : ''}>失效</option>
                </select>
            </div>
            <div class="mb-3">
                <label class="form-label">备注</label>
                <textarea class="form-control" id="jjlRemark" rows="2">${jjl.remark || ''}</textarea>
            </div>
        `);
        configModal.show();
    }
}

// ==================== 房屋信息管理 ====================
async function loadHouses() {
    try {
        const data = await apiRequest('/api/houses');
        const houses = data.data;
        
        if (houses.length === 0) {
            $('#houseTableBody').html('<tr><td colspan="6" class="text-center py-4">暂无数据</td></tr>');
            return;
        }
        
        let html = '';
        houses.forEach(h => {
            html += `
                <tr>
                    <td><strong>${h.house_scale}</strong></td>
                    <td><span class="badge bg-info">${h.feng_shui}</span></td>
                    <td>${h.build_cost}</td>
                    <td>${h.max_space}</td>
                    <td>${h.owner_name || '-'}</td>
                    <td>
                        <button class="btn btn-sm btn-outline-primary" onclick="editHouse('${h.id}')">
                            <i class="bi bi-pencil"></i>
                        </button>
                        <button class="btn btn-sm btn-outline-danger" onclick="deleteItem('house', '${h.id}', '${h.house_scale}')">
                            <i class="bi bi-trash"></i>
                        </button>
                    </td>
                </tr>
            `;
        });
        
        $('#houseTableBody').html(html);
    } catch (error) {
        console.error('加载房屋信息列表失败:', error);
        $('#houseTableBody').html('<tr><td colspan="6" class="text-center text-danger">加载失败</td></tr>');
    }
}

async function editHouse(id) {
    const data = await apiRequest('/api/houses');
    const house = data.data.find(h => h.id === id);
    
    if (house) {
        currentType = 'house';
        currentEditId = id;
        $('#modalTitle').text('✏️ 编辑房屋信息');
        $('#modalBody').html(`
            <div class="row">
                <div class="col-md-6 mb-3">
                    <label class="form-label">房屋规模 *</label>
                    <select class="form-select" id="houseScale" required>
                        <option value="普通" ${house.house_scale === '普通' ? 'selected' : ''}>普通</option>
                        <option value="华宅" ${house.house_scale === '华宅' ? 'selected' : ''}>华宅</option>
                        <option value="豪宅" ${house.house_scale === '豪宅' ? 'selected' : ''}>豪宅</option>
                    </select>
                </div>
                <div class="col-md-6 mb-3">
                    <label class="form-label">风水等级 *</label>
                    <input type="text" class="form-control" id="houseFengShui" value="${house.feng_shui}" required>
                </div>
                <div class="col-md-6 mb-3">
                    <label class="form-label">建造费用(万两) *</label>
                    <input type="text" class="form-control" id="houseBuildCost" value="${house.build_cost}" required>
                </div>
                <div class="col-md-6 mb-3">
                    <label class="form-label">最大空间 *</label>
                    <input type="text" class="form-control" id="houseMaxSpace" value="${house.max_space}" required>
                </div>
                <div class="col-md-12 mb-3">
                    <label class="form-label">房主角色名</label>
                    <input type="text" class="form-control" id="houseOwner" value="${house.owner_name || ''}">
                </div>
            </div>
        `);
        configModal.show();
    }
}

// ==================== 角色作用管理 ====================
async function loadRoleFunctions() {
    try {
        const data = await apiRequest('/api/role-functions');
        const roleFuncs = data.data;
        
        if (roleFuncs.length === 0) {
            $('#roleFuncTableBody').html('<tr><td colspan="3" class="text-center py-4">暂无数据</td></tr>');
            return;
        }
        
        let html = '';
        roleFuncs.forEach(rf => {
            html += `
                <tr>
                    <td><strong>${rf.role_function}</strong></td>
                    <td>${rf.remark || '-'}</td>
                    <td>
                        <button class="btn btn-sm btn-outline-primary" onclick="editRoleFunction(${rf.id})">
                            <i class="bi bi-pencil"></i>
                        </button>
                        <button class="btn btn-sm btn-outline-danger" onclick="deleteItem('roleFunc', ${rf.id}, '${rf.role_function}')">
                            <i class="bi bi-trash"></i>
                        </button>
                    </td>
                </tr>
            `;
        });
        
        $('#roleFuncTableBody').html(html);
    } catch (error) {
        console.error('加载角色作用列表失败:', error);
        $('#roleFuncTableBody').html('<tr><td colspan="3" class="text-center text-danger">加载失败</td></tr>');
    }
}

async function editRoleFunction(id) {
    const data = await apiRequest('/api/role-functions');
    const rf = data.data.find(r => r.id === id);
    
    if (rf) {
        currentType = 'roleFunc';
        currentEditId = id;
        $('#modalTitle').text('✏️ 编辑角色作用');
        $('#modalBody').html(`
            <div class="mb-3">
                <label class="form-label">角色作用 *</label>
                <input type="text" class="form-control" id="roleFunctionName" value="${rf.role_function}" required>
            </div>
            <div class="mb-3">
                <label class="form-label">备注</label>
                <textarea class="form-control" id="roleFunctionRemark" rows="3">${rf.remark || ''}</textarea>
            </div>
        `);
        configModal.show();
    }
}

// ==================== 通用方法 ====================
function showAddModal(type) {
    currentType = type;
    currentEditId = null;
    
    const titles = {
        'server': '➕ 添加服务器',
        'menpai': '➕ 添加门派',
        'task': '➕ 添加任务',
        'jjl': '➕ 添加将军令',
        'house': '➕ 添加房屋信息',
        'roleFunc': '➕ 添加角色作用'
    };
    
    $('#modalTitle').text(titles[type]);
    
    const forms = {
        'server': `
            <div class="mb-3">
                <label class="form-label">服务器名称 *</label>
                <input type="text" class="form-control" id="serverName" required>
            </div>
            <div class="mb-3">
                <label class="form-label">开服时间</label>
                <input type="date" class="form-control" id="serverStartTime">
            </div>
            <div class="mb-3">
                <label class="form-label">状态</label>
                <select class="form-select" id="serverStatus">
                    <option value="正常" selected>正常</option>
                    <option value="维护">维护</option>
                    <option value="停服">停服</option>
                </select>
            </div>
            <div class="mb-3">
                <label class="form-label">备注</label>
                <textarea class="form-control" id="serverRemarks" rows="3"></textarea>
            </div>
        `,
        'menpai': `
            <div class="mb-3">
                <label class="form-label">门派名称 *</label>
                <input type="text" class="form-control" id="menpaiName" required>
            </div>
            <div class="mb-3">
                <label class="form-label">种族 *</label>
                <select class="form-select" id="menpaiRace" required>
                    <option value="">请选择</option>
                    <option value="人族">人族</option>
                    <option value="仙族">仙族</option>
                    <option value="魔族">魔族</option>
                </select>
            </div>
            <div class="mb-3">
                <label class="form-label">门派地点 *</label>
                <input type="text" class="form-control" id="menpaiLocation" required>
            </div>
            <div class="mb-3">
                <label class="form-label">描述</label>
                <textarea class="form-control" id="menpaiDescription" rows="3"></textarea>
            </div>
        `,
        'task': `
            <div class="row">
                <div class="col-md-12 mb-3">
                    <label class="form-label">任务名称 *</label>
                    <input type="text" class="form-control" id="taskName" required>
                </div>
                <div class="col-md-6 mb-3">
                    <label class="form-label">任务类型 *</label>
                    <select class="form-select" id="taskType" required>
                        <option value="">请选择</option>
                        <option value="日常">日常</option>
                        <option value="师门">师门</option>
                        <option value="副本">副本</option>
                        <option value="活动">活动</option>
                        <option value="剧情">剧情</option>
                        <option value="奇遇">奇遇</option>
                        <option value="帮派">帮派</option>
                        <option value="周末">周末</option>
                    </select>
                </div>
                <div class="col-md-3 mb-3">
                    <label class="form-label">最低等级 *</label>
                    <input type="text" class="form-control" id="taskMinLevel" value="1" required>
                </div>
                <div class="col-md-3 mb-3">
                    <label class="form-label">最高等级</label>
                    <input type="text" class="form-control" id="taskMaxLevel" value="999">
                </div>
                <div class="col-md-6 mb-3">
                    <label class="form-label">每日次数</label>
                    <input type="text" class="form-control" id="taskDailyLimit" value="0">
                </div>
                <div class="col-md-6 mb-3">
                    <label class="form-label">预计耗时(分钟)</label>
                    <input type="text" class="form-control" id="taskDuration">
                </div>
                <div class="col-md-6 mb-3">
                    <label class="form-label">完成条件 *</label>
                    <input type="text" class="form-control" id="taskFinishCondition" required>
                </div>
                <div class="col-md-6 mb-3">
                    <label class="form-label">是否启用</label>
                    <select class="form-select" id="taskIsActive">
                        <option value="TRUE" selected>启用</option>
                        <option value="FALSE">禁用</option>
                    </select>
                </div>
            </div>
        `,
        'jjl': `
            <div class="mb-3">
                <label class="form-label">手机号 *</label>
                <input type="text" class="form-control" id="jjlPhone" placeholder="请输入手机号" required>
            </div>
            <div class="mb-3">
                <label class="form-label">设备</label>
                <input type="text" class="form-control" id="jjlDevice" placeholder="例如：iPhone 13 Pro">
            </div>
            <div class="mb-3">
                <label class="form-label">状态 *</label>
                <select class="form-select" id="jjlStatus" required>
                    <option value="生效" selected>生效</option>
                    <option value="失效">失效</option>
                </select>
            </div>
            <div class="mb-3">
                <label class="form-label">备注</label>
                <textarea class="form-control" id="jjlRemark" rows="2" placeholder="备注信息"></textarea>
            </div>
        `,
        'house': `
            <div class="row">
                <div class="col-md-6 mb-3">
                    <label class="form-label">房屋规模 *</label>
                    <select class="form-select" id="houseScale" required>
                        <option value="">请选择</option>
                        <option value="普通">普通</option>
                        <option value="华宅">华宅</option>
                        <option value="豪宅">豪宅</option>
                    </select>
                </div>
                <div class="col-md-6 mb-3">
                    <label class="form-label">风水等级 *</label>
                    <input type="text" class="form-control" id="houseFengShui" required>
                </div>
                <div class="col-md-6 mb-3">
                    <label class="form-label">建造费用(万两) *</label>
                    <input type="text" class="form-control" id="houseBuildCost" required>
                </div>
                <div class="col-md-6 mb-3">
                    <label class="form-label">最大空间 *</label>
                    <input type="text" class="form-control" id="houseMaxSpace" required>
                </div>
                <div class="col-md-6 mb-3">
                    <label class="form-label">所需技能等级 *</label>
                    <input type="text" class="form-control" id="houseSkillLevel" required>
                </div>
                <div class="col-md-6 mb-3">
                    <label class="form-label">所需体力 *</label>
                    <input type="text" class="form-control" id="housePhysical" required>
                </div>
                <div class="col-md-12 mb-3">
                    <label class="form-label">房主角色名</label>
                    <input type="text" class="form-control" id="houseOwner">
                </div>
            </div>
        `,
        'roleFunc': `
            <div class="mb-3">
                <label class="form-label">角色作用 *</label>
                <input type="text" class="form-control" id="roleFunctionName" required>
            </div>
            <div class="mb-3">
                <label class="form-label">备注</label>
                <textarea class="form-control" id="roleFunctionRemark" rows="3"></textarea>
            </div>
        `
    };
    
    $('#modalBody').html(forms[type]);
    configModal.show();
}

async function saveConfig() {
    try {
        let url, method, data;
        
        if (currentType === 'server') {
            data = {
                server_name: $('#serverName').val(),
                server_start_time: $('#serverStartTime').val(),
                status: $('#serverStatus').val(),
                remarks: $('#serverRemarks').val()
            };
            url = currentEditId ? `/api/servers/${currentEditId}` : '/api/servers';
            method = currentEditId ? 'PUT' : 'POST';
        } else if (currentType === 'menpai') {
            data = {
                name: $('#menpaiName').val(),
                race: $('#menpaiRace').val(),
                location: $('#menpaiLocation').val(),
                description: $('#menpaiDescription').val()
            };
            url = currentEditId ? `/api/menpai/${currentEditId}` : '/api/menpai';
            method = currentEditId ? 'PUT' : 'POST';
        } else if (currentType === 'task') {
            data = {
                task_name: $('#taskName').val(),
                task_type: $('#taskType').val(),
                min_level: $('#taskMinLevel').val(),
                max_level: $('#taskMaxLevel').val(),
                daily_limit: $('#taskDailyLimit').val(),
                duration_minutes: $('#taskDuration').val(),
                finish_condition: $('#taskFinishCondition')?.val() || '{}',
                is_active: $('#taskIsActive').val()
            };
            url = currentEditId ? `/api/tasks-list/${currentEditId}` : '/api/tasks-list';
            method = currentEditId ? 'PUT' : 'POST';
        } else if (currentType === 'jjl') {
            data = {
                phone: $('#jjlPhone').val(),
                device: $('#jjlDevice').val(),
                status: $('#jjlStatus').val(),
                remark: $('#jjlRemark').val()
            };
            url = currentEditId ? `/api/jiangjunling/${currentEditId}` : '/api/jiangjunling';
            method = currentEditId ? 'PUT' : 'POST';
        } else if (currentType === 'house') {
            data = {
                house_scale: $('#houseScale').val(),
                feng_shui: $('#houseFengShui').val(),
                build_cost: $('#houseBuildCost').val(),
                max_space: $('#houseMaxSpace').val(),
                required_skill_level: $('#houseSkillLevel')?.val() || '0',
                required_physical: $('#housePhysical')?.val() || '0',
                owner_name: $('#houseOwner').val()
            };
            url = currentEditId ? `/api/houses/${currentEditId}` : '/api/houses';
            method = currentEditId ? 'PUT' : 'POST';
        } else if (currentType === 'roleFunc') {
            data = {
                role_function: $('#roleFunctionName').val(),
                remark: $('#roleFunctionRemark').val()
            };
            url = currentEditId ? `/api/role-functions/${currentEditId}` : '/api/role-functions';
            method = currentEditId ? 'PUT' : 'POST';
        }
        
        await apiRequest(url, {
            method: method,
            body: JSON.stringify(data)
        });
        
        showNotification(currentEditId ? '更新成功' : '添加成功', 'success');
        configModal.hide();
        
        // 刷新对应列表
        if (currentType === 'server') loadServers();
        else if (currentType === 'menpai') loadMenpai();
        else if (currentType === 'task') loadTasks();
        else if (currentType === 'jjl') loadJiangjunling();
        else if (currentType === 'house') loadHouses();
        else if (currentType === 'roleFunc') loadRoleFunctions();
        
    } catch (error) {
        showNotification('操作失败: ' + error.message, 'error');
    }
}

async function deleteItem(type, id, name) {
    if (!confirm(`确定要删除"${name}"吗？`)) return;
    
    try {
        const urls = {
            'server': `/api/servers/${id}`,
            'menpai': `/api/menpai/${id}`,
            'task': `/api/tasks-list/${id}`,
            'jjl': `/api/jiangjunling/${id}`,
            'house': `/api/houses/${id}`,
            'roleFunc': `/api/role-functions/${id}`
        };
        
        await apiRequest(urls[type], { method: 'DELETE' });
        showNotification('删除成功', 'success');
        
        // 刷新对应列表
        if (type === 'server') loadServers();
        else if (type === 'menpai') loadMenpai();
        else if (type === 'task') loadTasks();
        else if (type === 'jjl') loadJiangjunling();
        else if (type === 'house') loadHouses();
        else if (type === 'roleFunc') loadRoleFunctions();
        
    } catch (error) {
        showNotification('删除失败: ' + error.message, 'error');
    }
}
</script>
{% endblock %}